package com.wys.ws_im.service;

import cn.hutool.core.util.StrUtil;
import com.wys.ws_im.dao.*;
import com.wys.ws_im.entity.Account;
import com.wys.ws_im.entity.Shop;
import com.wys.ws_im.entity.ShopService;
import com.wys.ws_im.exception.FrameErrorCodeEnums;
import com.wys.ws_im.exception.FrameRuntimeException;
import com.wys.ws_im.controller.LoginState;
import com.wys.ws_im.map.OnlineMap;
import com.wys.ws_im.vo.TokenVO;
import com.wys.ws_im.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 用户服务
 *
 * @author wys
 * created in 12:34 2019/4/9
 */
@Slf4j
@Service
public class UserService {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ShopDao shopDao;

    @Autowired
    private ShopServiceDao shopServiceDao;

    @Autowired
    private ServiceDao serviceDao;

    @Autowired
    private LoginState loginState;

    public TokenVO login(String account, String password) {
        Account user = accountDao.createLambdaQuery().andEq(Account::getAccount, account).single();

        if (user == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.ACCOUNT_NULL_ERROR);
        }
        System.out.println("user.getAccount() + user.getPassword() = " + user.getAccount() + user.getPassword());
        if ( !user.getAccount().equals(account) || !user.getPassword().equals(password) ) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.ACCOUNT_PASSWORD_ERROR);
        }

        TokenVO tokenVO = new TokenVO();
        tokenVO.setAid(user.getAid());
        tokenVO.setAvatarUrl(user.getAvatarUrl());
        tokenVO.setNickname(user.getNickName());
        tokenVO.setRole(user.getRole());

        return tokenVO;
    }

    /**
     * 登录成功，获取用户信息
     *
     * @return
     */
    public TokenVO loginInfo(String account) {

        TokenVO tokenVO = new TokenVO();
        LambdaQuery<Account> lambdaQuery = accountDao.createLambdaQuery();
        log.info("账号 {} 获取登录信息", account);
        Account user = lambdaQuery.andEq(Account::getAccount, account).single();

        tokenVO.setAid(user.getAid());
        tokenVO.setRole(user.getRole());
        tokenVO.setNickname(user.getNickName());
        tokenVO.setAvatarUrl(user.getAvatarUrl());

        return tokenVO;
    }

    /**
     * 退出
     * @param account
     * @return
     */
    public Boolean logout(String account) {
        if (account == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.BIND_ARGS_ERROR);
        }

        return Boolean.TRUE;

    }

    /**
     * 注册
     * @param account
     * @return
     */
    public Boolean register(Account account) {
        if (account == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.BIND_ARGS_ERROR);
        }

        LambdaQuery<Account> lambdaQuery = accountDao.createLambdaQuery();
        log.info("注册 {} ", account);
        Account aaccountBase = lambdaQuery.andEq(Account::getAccount, account.getAccount()).single();
        if (aaccountBase != null) {
            if (aaccountBase.getAccount().equals(account.getAccount()) || aaccountBase.getNickName().equals(account.getNickName())) {
                throw new FrameRuntimeException(FrameErrorCodeEnums.ACCOUNT_ERROR);
            }
        }

        Account accountNew = new Account();
        accountNew.setAccount(account.getAccount());
        accountNew.setNickName(account.getNickName());
        accountNew.setPhone(account.getPhone());
        accountNew.setPassword(account.getPassword());
        accountNew.setRole(account.getRole());
        accountNew.setCreatedTime(new Date());
        accountNew.setUpdatedTime(new Date());

        // ../img/u.JPG     用户0
        // ../img/s.JPG     客服1

        // 用户增加
        if (account.getRole() == 0) {
            accountNew.setAvatarUrl("../img/u.JPG");
        }

        // 客服增加
        if (account.getRole() == 1) {
            accountNew.setAvatarUrl("../img/s.JPG");
        }

        if (account.getRole() == 2) {
            accountNew.setAvatarUrl("");
        }

        try {
            accountDao.insert(accountNew, true);
        }catch (Exception e) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.BIND_ARGS_ERROR);
        }
        return Boolean.TRUE;

    }

    /**
     * shop 增加商店
     * @param shop
     * @return
     */
    public Boolean shop(Shop shop) {
        if (shop == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.BIND_ARGS_ERROR);
        }

        Shop shopBase = shopDao.createLambdaQuery()
                .andEq(Shop::getShop, shop.getShop())
                .single();

        // 商店已被注册
        if (shopBase != null) {
//            if (shopBase.getShop().equals(shop.getShop()) || shopBase.getShopId().equals(shop.getShopId())) {
                throw new FrameRuntimeException(FrameErrorCodeEnums.SHOP_ERROR);
//            }
        }

        // 店主id已注册有商店
        Shop shopBase2 = shopDao.createLambdaQuery()
                .andEq(Shop::getShopId, shop.getShopId())
                .single();
        if (shopBase2 != null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.ACCOUNT_SHOP_ERROR);
        }

        Account single = accountDao.createLambdaQuery()
                .andEq(Account::getAid, shop.getShopId())
                .single();
        if (single == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.ACCOUNT_NULL_ERROR);
        }
        if (single.getRole() != 2) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.ACCOUNT_ROLE_ERROR);
        }

        Shop shop1 = new Shop();
        shop1.setShop(shop.getShop());
        shop1.setShopInfo(shop.getShopInfo());
        shop1.setShopId(shop.getShopId());
        shopDao.insert(shop1, true);

        return Boolean.TRUE;

    }


    /**
     * 修改用户个人信息
     * @param
     * @return
     */
    public Boolean updateInfo(Integer aid, String address) {

        if (aid == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.BIND_ARGS_ERROR);
        }
        try {
            Account accountBase = accountDao.createLambdaQuery()
                    .andEq(Account::getAid, aid)
                    .single();
            if (accountBase == null) {
                throw new FrameRuntimeException(FrameErrorCodeEnums.ACCOUNT_NULL_ERROR);
            }
            accountBase.setAddress(address);
            accountDao.updateById(accountBase);

        }catch (Exception e) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.DB_ERROR);
        }

        return Boolean.TRUE;
    }

    /**
     * 修改客服个人信息
     * @param
     * @return
     */
    public Boolean updateServiceInfo(Integer aid, String phone) {

        if (aid == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.BIND_ARGS_ERROR);
        }

        try {
            Account accountBase = accountDao.createLambdaQuery()
                    .andEq(Account::getAid, aid)
                    .single();
            if (accountBase == null) {
                throw new FrameRuntimeException(FrameErrorCodeEnums.ACCOUNT_NULL_ERROR);
            }
            accountBase.setPhone(phone);
            accountDao.updateById(accountBase);

        }catch (Exception e) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.DB_ERROR);
        }

        return Boolean.TRUE;
    }

    /**
     * 增加客服
     * @param shopId
     * @param serviceName
     * @return
     */
    public Boolean addService(Integer shopId, String serviceName) {

        if (shopId == null || StrUtil.isBlank(serviceName)) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.BIND_ARGS_ERROR);
        }

        // 店主
        Account account = accountDao.createLambdaQuery()
                .andEq(Account::getAid, shopId)
                .single();
        if (account == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.ACCOUNT_NULL_ERROR);
        }

        // 商店
        Shop shop = shopDao.createLambdaQuery()
                .andEq(Shop::getShopId, shopId)
                .single();
        if (shop == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.SHOP_NULL_ERROR);
        }

        // 客服
        Account service = accountDao.createLambdaQuery()
                .andEq(Account::getNickName, serviceName)
                .single();
        if (service == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.SERVICE_NULL_ERROR);
        }
        ShopService shopService1 = shopServiceDao.createLambdaQuery()
                .andEq(ShopService::getServiceName, serviceName)
                .single();

        // 这个客服已被其他商店添加
        if (shopService1 != null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.SERVICE_HAVE_ERROR);
        }
        // 不是客服
        if (service.getRole() != 1) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.SERVICE_NOT_ERROR);
        }

        ShopService shopServiceBase = shopServiceDao.createLambdaQuery()
                .andEq(ShopService::getShopId, shopId)
                .andEq(ShopService::getServiceName, serviceName)
                .single();
        if (shopServiceBase != null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.SHOP_SERVICE_ALREADY);
        }

        ShopService shopService = new ShopService();
        shopService.setShopId(shop.getId());
        shopService.setServiceName(serviceName);
        shopServiceDao.insert(shopService);

        // service表增加
        com.wys.ws_im.entity.Service service1 = new com.wys.ws_im.entity.Service();
        log.info("setServiceId {}", service.getAid());
        service1.setServiceId(service.getAid());
        service1.setShop(shop.getShop());
        service1.setShopId(shop.getId());
        serviceDao.insert(service1);

        return Boolean.TRUE;
    }

    /**
     * 移除客服
     * @param shopId
     * @param serviceName
     * @return
     */
    public Boolean removeService(Integer shopId, String serviceName) {

        if (shopId == null ||StrUtil.isBlank(serviceName)) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.BIND_ARGS_ERROR);
        }

        Shop shop = shopDao.createLambdaQuery()
                .andEq(Shop::getShopId, shopId)
                .single();
        if (shop == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.SHOP_NULL_ERROR);
        }


        Account service = accountDao.createLambdaQuery()
                .andEq(Account::getNickName, serviceName)
                .single();
        if (service == null) {
            throw new FrameRuntimeException(FrameErrorCodeEnums.SERVICE_NULL_ERROR);
        }

        ShopService single = shopServiceDao.createLambdaQuery()
                .andEq(ShopService::getShopId, shop.getId())
                .andEq(ShopService::getServiceName, serviceName)
                .single();
        if (single != null) {
            shopServiceDao.deleteById(single.getId());
        }

        return Boolean.TRUE;

    }

    public String getStatus(Integer receviId) {

        Account account = accountDao.createLambdaQuery()
                .andEq(Account::getAid, receviId)
                .single();
        if (OnlineMap.onlineUserMap.containsKey(account.getAccount())) {
            return "在线";
        }
        return "离线";

    }

    /**
     * 获得账号
     */
    public List<Account> getAccount() {

        List<Account> accounts = accountDao.createLambdaQuery().select();
        return accounts;

    }

    /**
     * 获得账号
     */
    public List<Shop> getShop() {

        List<Shop> shops = shopDao.createLambdaQuery().select();
        return shops;

    }

    /**
     * 获得账号
     */
    public String getShopName(String serviceName) {

        ShopService shopService = shopServiceDao.createLambdaQuery()
                .andEq(ShopService::getServiceName, serviceName)
                .single();
        if (shopService != null) {
            Shop shop = shopDao.createLambdaQuery()
                    .andEq(Shop::getId, shopService.getShopId())
                    .single();
            return shop.getShop();
        }

        return "";

    }

}
